package com.one.common.view.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.one.common.R;
import com.one.common.utils.StringUtils;


/**
 * creator: zhulunjun
 * time:    2018/7/10
 * describe: 可输入多行文本，带字数限制的，
 * 使用场景： 分享内容，评论输入等
 */

public class BigEditView extends LinearLayout implements TextWatcher, View.OnTouchListener{

    private TextView tvTitle, tvNum;
    private EditText editText;
    private int maxNum;

    public BigEditView(Context context) {
        super(context);
    }

    public BigEditView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        if (attrs == null) {
            return;
        }
        LayoutInflater.from(context).inflate(R.layout.layout_big_edit, this);
        TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.BigEditView);
        String title = ta.getString(R.styleable.BigEditView_edit_title);
        int titleRes = ta.getResourceId(R.styleable.BigEditView_edit_title, -1);
        String hint = ta.getString(R.styleable.BigEditView_edit_hint);
        int hintRes = ta.getResourceId(R.styleable.BigEditView_edit_hint, -1);
        float height = ta.getDimension(R.styleable.BigEditView_edit_height, -1);
        int heightRes = ta.getResourceId(R.styleable.BigEditView_edit_height, -1);
        if (heightRes != -1) {
            heightRes = (int) context.getResources().getDimension(heightRes);
        }
        int num = ta.getInt(R.styleable.BigEditView_max_num, -1);
        int numRes = ta.getResourceId(R.styleable.BigEditView_max_num, -1);
        if (numRes != -1) {
            numRes = (int) context.getResources().getDimension(numRes);
        }
        int lines = ta.getInt(R.styleable.BigEditView_lines, -1);
        int linesRes = ta.getResourceId(R.styleable.BigEditView_lines, -1);
        if (linesRes != -1) {
            linesRes = (int) context.getResources().getDimension(linesRes);
        }

        initView();

        setTitle(title);
        setTitle(titleRes);
        setEditHeight((int) height);
        setEditHeight(heightRes);
        setMaxNum(num);
        setMaxNum(numRes);
        setEditLines(lines);
        setEditLines(linesRes);
        setHint(hint);
        setHint(hintRes);
        editText.addTextChangedListener(this);
    }


    @SuppressLint("ClickableViewAccessibility")
    private void initView() {
        tvTitle = (TextView) findViewById(R.id.tv_title);
        tvNum = (TextView) findViewById(R.id.tv_num);
        editText = (EditText) findViewById(R.id.et_text);
        editText.setOnTouchListener(this);
    }

    public void setTitle(String title) {
        if (StringUtils.isNotBlank(title)) {
            tvTitle.setVisibility(VISIBLE);
            tvTitle.setText(title);
        } else {
            tvTitle.setVisibility(GONE);
        }
    }

    public void setTitle(int title) {
        if (title != -1) {
            tvTitle.setVisibility(VISIBLE);
            tvTitle.setText(title);
        } else {
            tvTitle.setVisibility(GONE);
        }
    }

    public void setHint(String hint) {
        if (StringUtils.isNotBlank(hint)) {
            editText.setHint(hint);
        }
    }

    public void setHint(int hint) {
        if (hint != -1) {
            editText.setHint(hint);
        }
    }

    public void setEditHeight(int height) {
        if (height > 0) {
            LayoutParams layoutParams = (LayoutParams) editText.getLayoutParams();
            layoutParams.height = height;
            editText.setLayoutParams(layoutParams);
        }
    }

    public void setEditLines(int lines) {
        if (lines > 0) {
            editText.setLines(lines);
        }
    }

    public void setMaxNum(int num) {
        if (num > 0) {
            maxNum = num;
            editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(num)});
        }
    }

    public EditText getEditText() {
        return editText;
    }

    public String getText() {
        return editText.getText().toString();
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {


    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        tvNum.setText("字数限制（"+s.length() + "/" + maxNum+"）");
        if (s.length() > 0) {
            if (s.length() == maxNum) {
                tvNum.setTextColor(getContext().getResources().getColor(R.color.root_red));
            } else {
                tvNum.setTextColor(getContext().getResources().getColor(R.color.color_666666));
            }
        } else {
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }


    /**
     * EditText竖直方向是否可以滚动
     * @param editText  需要判断的EditText
     * @return  true：可以滚动   false：不可以滚动
     */
    private boolean canVerticalScroll(EditText editText) {
        //滚动的距离
        int scrollY = editText.getScrollY();
        //控件内容的总高度
        int scrollRange = editText.getLayout().getHeight();
        //控件实际显示的高度
        int scrollExtent = editText.getHeight() - editText.getCompoundPaddingTop() -editText.getCompoundPaddingBottom();
        //控件内容总高度与实际显示高度的差值
        int scrollDifference = scrollRange - scrollExtent;

        if(scrollDifference == 0) {
            return false;
        }

        return (scrollY > 0) || (scrollY < scrollDifference - 1);
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        //触摸的是EditText并且当前EditText可以滚动则将事件交给EditText处理；否则将事件交由其父类处理
        if ((view.getId() == R.id.et_text && canVerticalScroll(editText))) {
            view.getParent().requestDisallowInterceptTouchEvent(true);
            if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                view.getParent().requestDisallowInterceptTouchEvent(false);
            }
        }
        return false;
    }
}
